package cn.lil.servlet;

import cn.lil.model.Order;
import cn.lil.model.User;
import cn.lil.service.OrderService;
import cn.lil.service.UserService;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet(name = "UserLoginServlet", value = "/UserLoginServlet")
public class UserLoginServlet extends HttpServlet {
    UserService uService = new UserService();
    OrderService orderService = new OrderService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = uService.login(username, password);

        System.out.println(user);
        if (user == null) {
            request.setAttribute("failMsg", "请输入正确的账号和密码");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        } else {
            request.getSession().setAttribute("user", user);
            HttpSession session = request.getSession();
            session.setAttribute("isLogin", "true");
            // 转发到 BearingServlet
            if (user.getUsername().equals("ljl")) {
                request.getRequestDispatcher("/BearingServlet").forward(request, response);
            } else {
                List<Order> order = null;
                User u = (User) request.getSession().getAttribute("user");
                if (u == null) {
                    response.sendRedirect("/index.jsp");
                    return;
                }
                try {
                    order = orderService.selectAll(u.getId());
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                request.getSession().setAttribute("order", order.get(0));
                request.getRequestDispatcher("/uindex.jsp").forward(request, response);
            }

        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
